<?php
// 应用公共文件
use think\Controller;
use think\facade\Config;
use think\Request;
use think\Db;

use GatewayClient\Gateway;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Live\V20180801\LiveClient;
use TencentCloud\Live\V20180801\Models\DescribeLiveStreamOnlineListRequest;


# echo json
function Code($code=null,$msg=false,$data=false,$options=256){
    $array = [];
    $array["code"] = $code;
    (is_bool($msg) && !$msg) ? false : $array["msg"] = $msg;
    (is_bool($data) && !$data) ? false : $array["data"] = $data;
    echo json_encode($array, $options);
    exit();
}

# 上传文件
function UploadFile($arr, $name, $path, $suffix = false){
    $su = "jpg";
    if(is_string($suffix)){
        $su = $suffix;
    }else if(is_bool($suffix) && $suffix){
        $suffix = explode(".", $arr["name"]);
        $su = end($suffix);
    }

    $newname = $name.".".$su;
    if(!is_dir($path)){
        mkdir($path, 0777, true);
    }
    move_uploaded_file($arr["tmp_name"], $path.$newname);
    if(is_file($path.$newname)){
        return $newname;
    }else{
        return false;
    }
}

# 加上万单位
function float_number($number){
    $number = (float)$number;
    if($number >= 10000){
        $num = $number / 10000;
        if(is_int($num)){
            return $num."万";
        }else{
            return number_format($num, 0)."万";
        }
    }else{
        return $number;
    }
}

/* 毫秒时间戳 */
function msectime(){
    list($msec, $sec) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
}

/* 价格范围 */
function eval_price($array, $type=1){
    if($type == 1){
        $eval = [($array["begin_price"] == 0 ? "" : (float)$array["begin_price"]), ($array["end_price"] == 0 ? "" : (float)$array["end_price"])];
    }else{
        $eval = "";
        if($array["begin_price"] != 0 && $array["end_price"] != 0){
            $eval = float_number($array["begin_price"])." ~ ".float_number($array["end_price"]);
        }else{
            if($array["begin_price"] != 0){
                $eval = float_number($array["begin_price"]);
            }else if($array["end_price"] != 0){
                $eval = float_number($array["end_price"]);
            }
        }
    }

    return $eval;
}

function spec($array, $type=1){
    $spec = [];
    if($type == 1){
        if($array["size"] != ""){
            $spec[] = [
                "attr" => "规格",
                "val" => $array["size"]
            ];
        }
        if($array["remark"] != ""){
            $spec[] = [
                "attr" => "备注",
                "val" => $array["remark"]
            ];
        }
    }else if($type == 2){
        if($array["year"] != ""){
            $spec[] = [
                "attr" => "年代",
                "val" => $array["year"]
            ];
        }
        if($array["size"] != ""){
            $spec[] = [
                "attr" => "规格",
                "val" => $array["size"]
            ];
        }
        if($array["remark"] != ""){
            $spec[] = [
                "attr" => "备注",
                "val" => $array["remark"]
            ];
        }
    }else{
        if($array["size"] != ""){
            $spec[] = [
                "attr" => "规格",
                "val" => $array["size"]
            ];
        }
    }
    return $spec;
}

class Tran extends Controller{
    # 转换时间戳
    protected function TransformTime($time, $a, $b, $c){
        $y = date("Y", $time);
        $m = date("m", $time);
        $d = date("d", $time);
        return mktime($a,$b,$c,$m,$d,$y);
    }
}

class Common extends Tran {

    # token
    protected $token = null;

    # 检验token
    public function __construct(Request $request = null){
        parent::__construct();
        if(!method_exists($this, \request()->action())){
            Code(402, "Error, Empty");
        }else{
            if(\request()->action() != "login" && \request()->action() != "ocrbyidcard"){
                $arr = getallheaders();
                $token = $this->CheckToken1(isset($arr["Authorization"]) ? $arr["Authorization"] : "");
                $this->token = $token;
            }
        }
    }

    # 加密、解密方法  $string 需要加密文本 。$operation "D"为解密，E为加密
    private function encrypt($string,$operation,$key=null){
        if($key === null){
            $key = Config::get("app.tokenEncrypt");
        }
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return'';
            }
        }else{
            return str_replace('=','',base64_encode($result));
        }
    }

    # 生成Token
    protected function MakeToken($array){
        // 需要的值: aid、是否为七天登录、时间戳
        $string = json_encode($array,256);
        return $this->encrypt($string,"E")."d2";
    }

    # 发送ws到小组
    protected function sendTogrounp($arr=[], $grounp){
        Gateway::$registerAddress = Config::get("app.wsIp");
        Gateway::sendToGroup($grounp, json_encode($arr, 256));
    }

    # 搜索获取商品图片
    protected function SearchImg($LotID, $GoodID, $bool=false, $noimg=true, $urlname=false){
        # $bool false: 轮播图   true: 封面图
        if($bool){
            $dir = "./static/upload/detail/";
            if(is_file($dir."{$LotID}.jpg")){
                $image[] = Config::get("app.ip")."static/upload/detail/{$LotID}.jpg?t=".time();
            }else{
                $image[] = Config::get("app.ip")."static/image/no_img.jpg?t=".time();
            }
        }else{
            $dir = "./static/upload/detail/{$LotID}/";
            $image = [];
            if (is_dir($dir)){
                if ($dh = opendir($dir)){
                    while (($file = readdir($dh)) !== false){
                        switch ($LotID){
                            case 2 : case 3 : $GoodID = sprintf("%04d", $GoodID); break;
                            default : break;
                        }
                        $a = preg_match("/^$GoodID((-| |_)(.*))?\.(jpg|png)$/", $file, $match);
                        if($a){
                            if(count($match) == 5){
                                $image[] = Config::get("app.ip")."static/upload/detail/{$LotID}/".$file."?t=".time();
                            }
                        }
                    }
                    closedir($dh);
                }
            }
            if(empty($image) && $noimg){
                $image[] = Config::get("app.ip")."static/image/no_img.jpg?t=".time();
            }
        }

        sort($image, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
        if($urlname){
            $img = [];
            foreach ($image as $value){
                $img[] = ["url" => $value];
            }
            return $img;
        }else{
            return $image;
        }
    }

    protected function checkIsPush ($name, $id="", $key="", $domain=""){

        $id = Config::get("app.id");
        $key = Config::get("app.key");
        $domain = Config::get("app.domain");

        $cred = new Credential($id, $key);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("live.tencentcloudapi.com");

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new LiveClient($cred, "", $clientProfile);
        $req = new DescribeLiveStreamOnlineListRequest();
        $params = array(
            "DomainName" => $domain,
            "StreamName" => $name
        );
        $req->fromJsonString(json_encode($params));
        $resp = $client->DescribeLiveStreamOnlineList($req);
        $arr = json_decode($resp->toJsonString(), true);
        return !empty($arr["OnlineInfo"]);
    }

    protected function UploadDetailMap($arr, $lotid, $lid){
        if(!is_dir("./static/upload/detail/$lid")){
            mkdir("./static/upload/detail/$lid", 0777, true);
        }
        $img = $this->SearchImg($lid, $lotid, false, false);
        $number = count($img) + 1;
        $upload = count($arr["name"]);
        for ($i = 0; $i < $upload; $i++){
            switch ($lid){
                case 2 : case 3 : $lotid = sprintf("%04d", $lotid); break;
                default : break;
            }
            while (is_file("./static/upload/detail/$lid/$lotid-$number.jpg")){
                $number += 1;
            }
            move_uploaded_file($arr["tmp_name"][$i], "./static/upload/detail/$lid/$lotid-$number.jpg");
        }
    }

    protected function SearchImgAppend($LotID, $GoodID, $noimg=false){
        $dir = "./static/upload/append/{$LotID}/";
        $image = [];
        if (is_dir($dir)){
            if ($dh = opendir($dir)){
                while (($file = readdir($dh)) !== false){
                    switch ($LotID){
                        case 2 : case 3 : $GoodID = sprintf("%04d", $GoodID); break;
                        default : break;
                    }
                    $a = preg_match("/^$GoodID((-| |_)(.*))?\.(jpg|png)$/", $file, $match);
                    if($a){
                        if(count($match) == 5){
                            $image[] = Config::get("app.ip")."static/upload/append/{$LotID}/".$file."?t=".time();
                        }
                    }
                }
                closedir($dh);
            }
        }
        if(empty($image) && $noimg){
            $image[] = Config::get("app.ip")."static/image/no_img.jpg?t=".time();
        }
        sort($image, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
        $img = [];
        foreach ($image as $value){
            $img[] = ["url" => $value];
        }
        return $img;
    }

    protected function UploadAppendMap($arr, $lotid, $lid){
        if(!is_dir("./static/upload/append/$lid")){
            mkdir("./static/upload/append/$lid", 0777, true);
        }
        $img = $this->SearchImgAppend($lid, $lotid);
        $number = count($img) + 1;
        $upload = count($arr["name"]);
        for ($i = 0; $i < $upload; $i++){
            switch ($lid){
                case 2 : case 3 : $lotid = sprintf("%04d", $lotid); break;
                default : break;
            }
            while (is_file("./static/upload/append/$lid/$lotid-$number.jpg")){
                $number += 1;
            }
            move_uploaded_file($arr["tmp_name"][$i], "./static/upload/append/$lid/$lotid-$number.jpg");
        }
    }

    # 获取获拍人的信息
    protected function GetPeople($arr){
        $num = false;
        if($arr["nid"] != 0){

            $n = \think\Db::name("num")->where("nid", $arr["nid"])->find();
            $num = (int)$n["number"];
        }else if($arr["up_id"] != 0){
            $admin = Db::name("user_proxy")->where("up_id", $arr["up_id"])->find();
            $num = $admin["name"];
        }

        return $num;
    }

    # 获取spec字段  size | remark | year
    protected function Spec($array, $type=["size" => "规格", "remark" => "备注", "year" => "年代"]){
        $spec = [];
        foreach ($type as $key => $t){
            if($array[$key] != ""){
                $spec[] = [
                    "attr" => $t,
                    "val" => $array[$key]
                ];
            }
        }
        return $spec;
    }

    # 获取最终价格
    protected function GetFinal($arr, $bool=true){
        if($bool){
            return $arr["state"] == 0 ? "" : $arr["state"] == 6 ? "流拍" : ($arr["state"] == 3 || $arr["state"] == 4 || $arr["state"] == 5) ? $arr["final_price"] : "";
        }else{
            return $arr["state"] == 0 ? "" : $arr["state"] == 6 ? "流拍" : ($arr["state"] == 3 || $arr["state"] == 4 || $arr["state"] == 5) ? (float)$arr["final_price"] : "";
        }
    }

    # 格式化价格范围
    protected function EvalPrice($array, $type=1){
        if($type == 1){
            $eval = [($array["begin_price"] == 0 ? "" : (float)$array["begin_price"]), ($array["end_price"] == 0 ? "" : (float)$array["end_price"])];
        }else{
            $eval = "";
            if($array["begin_price"] != 0 && $array["end_price"] != 0){
                $eval = float_number($array["begin_price"])." ~ ".float_number($array["end_price"]);
            }else{
                if($array["begin_price"] != 0){
                    $eval = float_number($array["begin_price"]);
                }else if($array["end_price"] != 0){
                    $eval = float_number($array["end_price"]);
                }
            }
        }

        return $eval;
    }

    # 获取直播二维码
    protected function getPushUrl($streamName, $time, $domain = null, $key = null){
        if($domain === null){
            $domain = Config::get("app.domain");
        }
        if($key === null){
            $key = Config::get("app.key");
        }
        if($key && $time){
            $txTime = strtoupper(base_convert(strtotime($time),10,16));
            //txSecret = MD5( KEY + streamName + txTime )
            $txSecret = md5($key.$streamName.$txTime);
            $ext_str = "?".http_build_query(array(
                    "txSecret"=> $txSecret,
                    "txTime"=> $txTime
                ));
        }
        return "rtmp://".$domain."/live/".$streamName . (isset($ext_str) ? $ext_str : "");
    }

    # 生成秘钥Excel
    protected function GetNumExcel($filename, $aid=0){
        $data = Db::name("num")->where("aid", $aid)->order("ub_id asc, number asc")->select();
        $count = Db::name("num")->where("aid", $aid)->count();
        if(!empty($data)){
            $obj = new PHPExcel();

            # 以下内容是excel文件的信息描述信息
            $obj->getProperties()->setCreator('admin'); # 设置创建者
            $obj->getProperties()->setLastModifiedBy('admin'); #设置修改者
            $obj->getProperties()->setTitle('秘钥'); #设置标题
            $obj->getProperties()->setSubject('秘钥'); #设置主题
            $obj->getProperties()->setDescription('秘钥'); #设置描述
            $obj->getProperties()->setKeywords('secret'); # 设置关键词
            $obj->getProperties()->setCategory('result file'); # 设置类型

            # 设置当前sheet
            $obj->setActiveSheetIndex(0);

            # 设置当前sheet的名称
            $obj->getActiveSheet()->setTitle('秘钥');

            # 列标
            $list = ['A', 'B', 'C'];

            # 填充第一行数据
            $obj->getActiveSheet()
                ->setCellValue($list[0] . '1', '号码')
                ->setCellValue($list[1] . '1', '秘钥')
                ->setCellValue($list[2] . '1', '是否使用');

            # 填充第n(n>=2, n∈N*)行数据
            for ($i = 0; $i < $count; $i++) {
                $obj->getActiveSheet()->setCellValue($list[0] . ($i + 2), $data[$i]["number"], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
                $obj->getActiveSheet()->setCellValue($list[1] . ($i + 2), $data[$i]["password"]);
                $obj->getActiveSheet()->setCellValue($list[2] . ($i + 2), $data[$i]["ub_id"] == 0 ? "0" : "1");
            }

            # 设置加粗和左对齐
            foreach ($list as $col) {
                # 设置第一行加粗
                $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
                # 设置第1-n行，左对齐
                for ($i = 1; $i <= $count + 1; $i++) {
                    $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                }
            }

            # 设置列宽
            $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $obj->getActiveSheet()->getColumnDimension('B')->setWidth(20);

            # 导出
            ob_clean();

            $objWriter = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            if(!is_dir("./static/upload/num/{$aid}")){
                mkdir("./static/upload/num/{$aid}",0777,true);
            }
            if($handle = opendir("./static/upload/num/{$aid}")){
                while ($file = readdir($handle)){
                    if($file == "." || $file == ".."){
                        continue;
                    }
                    unlink("./static/upload/num/{$aid}/$file");
                }
            }
            $objWriter->save("static/upload/num/{$aid}/{$filename}.xlsx");
            if(is_file("./static/upload/num/{$aid}/{$filename}.xlsx")){
                return Config::get("app.ip")."static/upload/num/{$aid}/{$filename}.xlsx";
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    # 导出成交记录
    public function TransactionRecord($filename, $data){
        $count = count($data);
        if(!empty($data)){
            $obj = new PHPExcel();

            # 以下内容是excel文件的信息描述信息
            $obj->getProperties()->setCreator('admin'); # 设置创建者
            $obj->getProperties()->setLastModifiedBy('admin'); #设置修改者
            $obj->getProperties()->setTitle('成交记录'); #设置标题
            $obj->getProperties()->setSubject('成交记录'); #设置主题
            $obj->getProperties()->setDescription('成交记录'); #设置描述
            $obj->getProperties()->setKeywords('secret'); # 设置关键词
            $obj->getProperties()->setCategory('result file'); # 设置类型
            # 设置当前sheet
            $obj->setActiveSheetIndex(0);
            # 设置当前sheet的名称
            $obj->getActiveSheet()->setTitle('成交记录');
            # 列标
            $list = ['A', 'B', 'C', 'D', 'E', 'F'];
            # 填充第一行数据
            $obj->getActiveSheet()
                ->setCellValue($list[0] . '1', '图录号')
                ->setCellValue($list[1] . '1', '拍品名称')
                ->setCellValue($list[2] . '1', '成交价')
                ->setCellValue($list[3] . '1', '买家号牌')
                ->setCellValue($list[4] . '1', '买家姓名')
                ->setCellValue($list[5] . '1', '电话号码');
            # 填充第n(n>=2, n∈N*)行数据
            for ($i = 0; $i < $count; $i++) {
                $obj->getActiveSheet()->setCellValue($list[0] . ($i + 2), $data[$i]["lotnum"], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
                $obj->getActiveSheet()->setCellValue($list[1] . ($i + 2), $data[$i]["goodname"]);
                $obj->getActiveSheet()->getStyle($list[2] . ($i + 2))->getNumberFormat()->setFormatCode('￥ #,##0');
                $obj->getActiveSheet()->setCellValue($list[2] . ($i + 2), $data[$i]["final_price"] == 0 ? '' : $data[$i]["final_price"]);
                $obj->getActiveSheet()->setCellValue($list[3] . ($i + 2), $data[$i]["number"] == 0 ? '' : $data[$i]["number"]);
                $obj->getActiveSheet()->setCellValue($list[4] . ($i + 2), $data[$i]["username"] == 'NULL' ? '' : $data[$i]["username"]);
                $obj->getActiveSheet()->setCellValue($list[5] . ($i + 2), $data[$i]["tel1"] == 'NULL' ? '' : $data[$i]["tel1"]);
            }
            # 设置加粗和左对齐
            foreach ($list as $col) {
                # 设置第一行加粗
                $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
                # 设置第1-n行，左对齐
                for ($i = 1; $i <= $count + 1; $i++) {
                    $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                }
            }

            # 设置列宽
            $obj->getActiveSheet()->getColumnDimension('A')->setWidth(10);
            $obj->getActiveSheet()->getColumnDimension('B')->setWidth(40);
            $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $obj->getActiveSheet()->getColumnDimension('D')->setWidth(10);
            $obj->getActiveSheet()->getColumnDimension('E')->setWidth(10);
            $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);

            # 导出
            ob_clean();

            $objWriter = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            if(!is_dir("./static/upload/transactionRecord")){
                mkdir("./static/upload/transactionRecord",0777,true);
            }
            if($handle = opendir("./static/upload/transactionRecord")){
                while ($file = readdir($handle)){
                    if($file == "." || $file == ".."){
                        continue;
                    }
                    unlink("./static/upload/transactionRecord/$file");
                }
            }
            $objWriter->save("static/upload/transactionRecord/{$filename}.xlsx");
            if(is_file("./static/upload/transactionRecord/{$filename}.xlsx")){
                return Config::get("app.ip")."static/upload/transactionRecord/{$filename}.xlsx";
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    # 导入拍品
    protected function ImportAuction($file, $lid, $send_id){
        $objPHPExcelReader = PHPExcel_IOFactory::load($file);

        $sheet = $objPHPExcelReader->getSheet(0); // 读取第一个工作表(编号从 0 开始)
        $highestRow = $sheet->getHighestRow();           // 取得总行数
        $highestColumn = $sheet->getHighestColumn();     // 取得总列数

        $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T');
        $vv = array();
        $number = $name = $price = $lib_number = $level = $classname = $recommend = $author = $summary = $year = $style = $size = $appendix = $resr_price = $begin = $end = $remark = $location = $report = null;
        for ($row = 1; $row <= $highestRow; $row++) {
            $row_arr = array();
            for ($column = 0; $arr[$column] != 'T'; $column++) {
                $val = $sheet->getCellByColumnAndRow($column, $row)->getCalculatedValue();
                $row_arr[] = $val;
                if($row == 1){
                    switch ($val){
                        case "图录号" : case "圖錄號" :  $number = $column; break;
                        case "拍品名称" : case "拍品名稱" : $name = $column; break;
                        case "起拍价" : case "起拍價" : $price = $column; break;
                        case "送货人ID" : case "送貨人ID" : $us_id = $column; break;
                        case "库位" : $location = $column; break;
                        case "库号" : case "庫號" : $lib_number = $column; break;
                        case "級別" : $level = $column; break;
                        case "分类" : case "分類" : $classname = $column; break;
                        case "推荐" : case "推薦" : $recommend = $column; break;
                        case "作者" : $author = $column; break;
                        case "作者简介" : case "作者簡介" : $summary = $column; break;
                        case "朝代" : $year = $column; break;
                        case "款识" : case "款識" : $style = $column; break;
                        case "规格" : case "規格" : $size = $column; break;
                        case "附属品" : case "附屬品" : $appendix = $column; break;
                        case "底价" : case "底價" : $resr_price = $column; break;
                        case "起始估价" : case "起始估價" : $begin = $column; break;
                        case "截止估价" : case "截止估價" : $end = $column; break;
                        case "备注" : case "備註" : $remark = $column; break;
                        case "品项报告" : case "品項報告" : $report = $column; break;
                    }
                }
            }
            $vv[] = $row_arr;
        }

        $count = 0;
        if(!empty($vv)){
            array_shift($vv);
            foreach ($vv as $key => $value){
                if(isset($value[$name]) && isset($value[$number]) && $value[$name] != "" && $value[$number] != "" && $value["$number"] != NULL){
                    $add = [
                        'lid' => $lid,
                        'us_id' => $value[$us_id],
                        'number' => $value[$number],
                        'name' => ($name === null || $value[$name] == NULL) ? "" : $value[$name],
                        'location' => ($location === null || $value[$location] == NULL) ? "" : $value[$location],
                        'price' => ($price == null || $value[$price] == NULL) ? Config::get("app.start_price") : $value[$price],
                        'lib_number' => ($lib_number == null || $value[$lib_number] == NULL) ? "" : $value[$lib_number],
                        'level' => ($level == null || $value[$level] == NULL) ? "" : $value[$level],
                        'classname' => ($classname == null || $value[$classname] == NULL) ? "" : $value[$classname],
                        'recommend' => ($recommend == null || $value[$recommend] == NULL) ? "" : $value[$recommend],
                        'author' => ($author == null || $value[$author] == NULL) ? "" : $value[$author],
                        'summary' => ($summary == null || $value[$summary] == NULL) ? "" : $value[$summary],
                        'year' => ($year == null || $value[$year] == NULL) ? "" : $value[$year],
                        'style' => ($style == null || $value[$style] == NULL) ? "" : $value[$style],
                        'size' => ($size == null || $value[$size] == NULL) ? "" : $value[$size],
                        'appendix' => ($appendix == null || $value[$appendix] == NULL) ? "" : $value[$appendix],
                        'resr_price' => ($resr_price == null || $value[$resr_price] == NULL) ? 0 : $value[$resr_price],
                        'begin_price' => ($begin == null || $value[$begin] == NULL) ? 0 : $value[$begin],
                        'end_price' => ($end == null || $value[$end] == NULL) ? 0 : $value[$end],
                        'report' => ($report == null || $value[$report] == NULL) ? "" : $value[$report],
                        'remark' => ($remark == null || $value[$remark] == NULL) ? "" : $value[$remark],
                        'state' => 0,
                    ];
                    Db::name("goods")->insert($add);
                    $count++;
                }else{
                    break;
                }
            }
        }

        return $count;
    }

    # 保证金操作存根
    protected function RecordMoney($uid, $aid, $moneyBefor, $moneyAfter, $remark, $state){
        # state 1是交钱 2是提现 -1是其他操作（扣钱等）
        $info = [
            "aid" => $aid,
            "ub_id" => $uid,
            "moneyBefore" => $moneyBefor,
            "moneyAfter" => $moneyAfter,
            "state" => $state,
            "remark" => $remark,
            "time" => time()
        ];
        Db::name("record")->insert($info);
    }

    # 检查token
    protected function CheckToken1($string){
        $str = substr($string,-2);
        if($str === "d2"){
            $new_str = substr($string,0,strlen($string)-2);
            $info = $this->encrypt($new_str,"D");
            $user = json_decode($info,true);
            if(isset($user["time"]) && isset($user["aid"]) && isset($user["table"])){
                $time = $user["time"];
                if($time+60*60*24*7 < time()){
                    # token过期
                    Code(901, "身份验证已过期，请重新登录");
                }else{
                    $admin = Db::name("admin")->where("aid",$user["aid"])->find();
                    if(empty($admin)){
                        # 管理员不存在，token违法
                        Code(801, "非法身份登录");
                    }else{
                        if(isset($user["pid"])){
                            return [
                                "id" => $user["aid"],
                                "pid" => $user["pid"],
                                "table" => $user["table"]
                            ];
                        }else{
                            return [
                                "id" => $user["aid"],
                                "table" => $user["table"]
                            ];
                        }
                    }
                }
            }else{
                # token违法
                Code(801, "非法身份登录");
            }
        }else{
            # token违法
            Code(801, "非法身份登录");
        }
        return false;
    }

    # 用户检查Token
    public function Check($string){
        $str = substr($string,-2);
        if($str === "d2"){
            $new_str = substr($string,0,strlen($string)-2);
            $admin = $this->encrypt($new_str,"D");
            $user = json_decode($admin,true);
            $token_info = ['time','id'];
            if(isset($user["time"]) && isset($user["id"])){
                $time = $user["time"];
                if($time+60*60*24*7 < time()){
                    // token过期
                    Code(901, "身份验证已过期，请重新登录");
                }else{
                    $admin = Db::name("user_buy")->where("ub_id",$user["id"])->find();
                    if(empty($admin)){
                        // 管理员不存在，token违法
                        Code(801, "非法身份登录");
                    }else{
                        return [
                            "id" => $user["id"]
                        ];
                    }
                }
            }else{
                // token违法
                Code(801, "非法身份登录");
            }
        }else{
            // token违法
            Code(801, "非法身份登录");
        }
    }

}

class Common1 extends Tran {

    # 加密、解密方法  $string 需要加密文本 。$operation "D"为解密，E为加密
    private function encrypt($string,$operation,$key=null){
        if($key === null){
            $key = Config::get("app.tokenEncrypt");
        }
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return'';
            }
        }else{
            return str_replace('=','',base64_encode($result));
        }
    }

    # 生成Token
    protected function MakeToken($array){
        // 需要的值: aid、是否为七天登录、时间戳
        $string = json_encode($array,256);
        return $this->encrypt($string,"E")."d2";
    }

    # 发送ws到小组
    protected function sendTogrounp($arr=[], $grounp){
        Gateway::$registerAddress = Config::get("app.wsIp");
        Gateway::sendToGroup($grounp, json_encode($arr, 256));
    }

    # 搜索获取商品图片
    protected function SearchImg($LotID, $GoodID, $bool=false, $noimg=true){
        # $bool false: 轮播图   true: 封面图
        if($bool){
            $dir = "./static/upload/detail/";
            if(is_dir($dir.$LotID) && is_file($dir."{$LotID}/{$LotID}.jpg")){
                $image[] = Config::get("app.ip")."static/upload/detail/{$LotID}.jpg?t=".time();
            }else{
                $image[] = Config::get("app.ip")."static/image/no_img.jpg?t=".time();
            }
        }else{
            $dir = "./static/upload/detail/{$LotID}/";
            $image = [];
            if (is_dir($dir)){
                if ($dh = opendir($dir)){
                    while (($file = readdir($dh)) !== false){
                        switch ($LotID){
                            case 2 : case 3 : $GoodID = sprintf("%04d", $GoodID); break;
                            default : break;
                        }
                        $a = preg_match("/^$GoodID((-| |_)(.*))?\.(jpg|png)$/", $file, $match);
                        if($a){
                            if(count($match) == 5){
                                $image[] = Config::get("app.ip")."static/upload/detail/{$LotID}/".$file."?t=".time();
                            }
                        }
                    }
                    closedir($dh);
                }
            }
            if(empty($image) && $noimg){
                $image[] = Config::get("app.ip")."static/image/no_img.jpg?t=".time();
            }
        }

        sort($image, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
        return $image;
    }

    protected function checkIsPush ($name, $id="", $key="", $domain=""){

        $id = Config::get("app.id");
        $key = Config::get("app.key1");
        $domain = Config::get("app.domain");

        $cred = new Credential($id, $key);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("live.tencentcloudapi.com");

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new LiveClient($cred, "", $clientProfile);
        $req = new DescribeLiveStreamOnlineListRequest();
        $params = array(
            "DomainName" => $domain,
            "StreamName" => $name
        );
        $req->fromJsonString(json_encode($params));
        $resp = $client->DescribeLiveStreamOnlineList($req);
        $arr = json_decode($resp->toJsonString(), true);
        return !empty($arr["OnlineInfo"]);
    }

    protected function UploadDetailMap($arr, $lotid, $lid){
        if(!is_dir("./static/upload/detail/$lid")){
            mkdir("./static/upload/detail/$lid", 0777, true);
        }
        $img = $this->SearchImg($lid, $lotid, false, false);
        $number = count($img) + 1;
        $upload = count($arr["name"]);
        for ($i = 0; $i < $upload; $i++){
            switch ($lid){
                case 2 : case 3 : $lotid = sprintf("%04d", $lotid); break;
                default : break;
            }
            while (is_file("./static/upload/detail/$lid/$lotid-$number.jpg")){
                $number += 1;
            }
            move_uploaded_file($arr["tmp_name"][$i], "./static/upload/detail/$lid/$lotid-$number.jpg");
        }
    }

    protected function SearchImgAppend($LotID, $GoodID, $noimg=false){
        $dir = "./static/upload/append/{$LotID}/";
        $image = [];
        if (is_dir($dir)){
            if ($dh = opendir($dir)){
                while (($file = readdir($dh)) !== false){
                    switch ($LotID){
                        case 2 : case 3 : $GoodID = sprintf("%04d", $GoodID); break;
                        default : break;
                    }
                    $a = preg_match("/^$GoodID((-| |_)(.*))?\.(jpg|png)$/", $file, $match);
                    if($a){
                        if(count($match) == 5){
                            $image[] = Config::get("app.ip")."static/upload/append/{$LotID}/".$file."?t=".time();
                        }
                    }
                }
                closedir($dh);
            }
        }
        if(empty($image) && $noimg){
            $image[] = Config::get("app.ip")."static/image/no_img.jpg?t=".time();
        }
        sort($image, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
        $img = [];
        foreach ($image as $value){
            $img[] = ["url" => $value];
        }
        return $img;
    }

    protected function UploadAppendMap($arr, $lotid, $lid){
        if(!is_dir("./static/upload/append/$lid")){
            mkdir("./static/upload/append/$lid", 0777, true);
        }
        $img = $this->SearchImgAppend($lid, $lotid);
        $number = count($img) + 1;
        $upload = count($arr["name"]);
        for ($i = 0; $i < $upload; $i++){
            switch ($lid){
                case 2 : case 3 : $lotid = sprintf("%04d", $lotid); break;
                default : break;
            }
            while (is_file("./static/upload/append/$lid/$lotid-$number.jpg")){
                $number += 1;
            }
            move_uploaded_file($arr["tmp_name"][$i], "./static/upload/append/$lid/$lotid-$number.jpg");
        }
    }

    # 获取获拍人的信息
    protected function GetPeople($arr){
        $num = false;
        if($arr["nid"] != 0){
            $n = Db::name("num")->where("nid", $arr["nid"])->find();
            $num = (int)$n["number"];
        }else if($arr["up_id"] != 0){
            $admin = Db::name("user_proxy")->where("up_id", $arr["up_id"])->find();
            $num = $admin["name"];
        }

        return $num;
    }

    # 获取spec字段  size | remark | year
    protected function Spec($array, $type=["size" => "规格", "remark" => "备注", "year" => "年代"]){
        $spec = [];
        foreach ($type as $key => $t){
            if($array[$key] != ""){
                $spec[] = [
                    "attr" => $t,
                    "val" => $array[$key]
                ];
            }
        }
        return $spec;
    }

    # 获取最终价格
    protected function GetFinal($arr, $bool=true){
        if($bool){
            return $arr["state"] == 0 ? "" : $arr["state"] == 6 ? "流拍" : ($arr["state"] == 3 || $arr["state"] == 4 || $arr["state"] == 5) ? $arr["final_price"] : "";
        }else{
            return $arr["state"] == 0 ? "" : $arr["state"] == 6 ? "流拍" : ($arr["state"] == 3 || $arr["state"] == 4 || $arr["state"] == 5) ? (float)$arr["final_price"] : "";
        }
    }

    # 格式化价格范围
    protected function EvalPrice($array, $type=1){
        if($type == 1){
            $eval = [($array["begin_price"] == 0 ? "" : (float)$array["begin_price"]), ($array["end_price"] == 0 ? "" : (float)$array["end_price"])];
        }else{
            $eval = "";
            if($array["begin_price"] != 0 && $array["end_price"] != 0){
                $eval = float_number($array["begin_price"])." ~ ".float_number($array["end_price"]);
            }else{
                if($array["begin_price"] != 0){
                    $eval = float_number($array["begin_price"]);
                }else if($array["end_price"] != 0){
                    $eval = float_number($array["end_price"]);
                }
            }
        }

        return $eval;
    }

    # 获取直播二维码
    protected function getPushUrl($streamName, $time, $domain = null, $key = null){
        if($domain === null){
            $domain = Config::get("app.domain");
        }
        if($key === null){
            $key = Config::get("app.key");
        }
        if($key && $time){
            $txTime = strtoupper(base_convert(strtotime($time),10,16));
            //txSecret = MD5( KEY + streamName + txTime )
            $txSecret = md5($key.$streamName.$txTime);
            $ext_str = "?".http_build_query(array(
                    "txSecret"=> $txSecret,
                    "txTime"=> $txTime
                ));
        }
        return "rtmp://".$domain."/live/".$streamName . (isset($ext_str) ? $ext_str : "");
    }

    # 生成秘钥Excel
    protected function GetNumExcel($filename, $aid=0){
        $data = Db::name("num")->where("aid", $aid)->order("ub_id asc, number asc")->select();
        $count = Db::name("num")->where("aid", $aid)->count();
        if(!empty($data)){
            $obj = new PHPExcel();

            # 以下内容是excel文件的信息描述信息
            $obj->getProperties()->setCreator('admin'); # 设置创建者
            $obj->getProperties()->setLastModifiedBy('admin'); #设置修改者
            $obj->getProperties()->setTitle('秘钥'); #设置标题
            $obj->getProperties()->setSubject('秘钥'); #设置主题
            $obj->getProperties()->setDescription('秘钥'); #设置描述
            $obj->getProperties()->setKeywords('secret'); # 设置关键词
            $obj->getProperties()->setCategory('result file'); # 设置类型

            # 设置当前sheet
            $obj->setActiveSheetIndex(0);

            # 设置当前sheet的名称
            $obj->getActiveSheet()->setTitle('秘钥');

            # 列标
            $list = ['A', 'B', 'C'];

            # 填充第一行数据
            $obj->getActiveSheet()
                ->setCellValue($list[0] . '1', '号码')
                ->setCellValue($list[1] . '1', '秘钥')
                ->setCellValue($list[2] . '1', '是否使用');

            # 填充第n(n>=2, n∈N*)行数据
            for ($i = 0; $i < $count; $i++) {
                $obj->getActiveSheet()->setCellValue($list[0] . ($i + 2), $data[$i]["number"], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
                $obj->getActiveSheet()->setCellValue($list[1] . ($i + 2), $data[$i]["password"]);
                $obj->getActiveSheet()->setCellValue($list[2] . ($i + 2), $data[$i]["ub_id"] == 0 ? "0" : "1");
            }

            # 设置加粗和左对齐
            foreach ($list as $col) {
                # 设置第一行加粗
                $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
                # 设置第1-n行，左对齐
                for ($i = 1; $i <= $count + 1; $i++) {
                    $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                }
            }

            # 设置列宽
            $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $obj->getActiveSheet()->getColumnDimension('B')->setWidth(20);

            # 导出
            ob_clean();

            $objWriter = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            if(!is_dir("./static/upload/num/{$aid}")){
                mkdir("./static/upload/num/{$aid}",0777,true);
            }
            if($handle = opendir("./static/upload/num/{$aid}")){
                while ($file = readdir($handle)){
                    if($file == "." || $file == ".."){
                        continue;
                    }
                    unlink("./static/upload/num/{$aid}/$file");
                }
            }
            $objWriter->save("static/upload/num/{$aid}/{$filename}.xlsx");
            if(is_file("./static/upload/num/{$aid}/{$filename}.xlsx")){
                return Config::get("app.ip")."static/upload/num/{$aid}/{$filename}.xlsx";
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    # 保证金操作存根
    protected function RecordMoney($uid, $aid, $moneyBefor, $moneyAfter, $remark, $state){
        # state 1是交钱 2是提现 -1是其他操作（扣钱等）
        $info = [
            "aid" => $aid,
            "ub_id" => $uid,
            "moneyBefore" => $moneyBefor,
            "moneyAfter" => $moneyAfter,
            "state" => $state,
            "remark" => $remark,
            "time" => time()
        ];
        Db::name("record")->insert($info);
    }

    # 检查token
    protected function CheckToken1($string){
        $str = substr($string,-2);
        if($str === "d2"){
            $new_str = substr($string,0,strlen($string)-2);
            $info = $this->encrypt($new_str,"D");
            $user = json_decode($info,true);
            if(isset($user["time"]) && isset($user["aid"]) && isset($user["table"])){
                $time = $user["time"];
                if($time+60*60*24*7 < time()){
                    # token过期
                    Code(901, "身份验证已过期，请重新登录");
                }else{
                    $admin = Db::name("admin")->where("aid",$user["aid"])->find();
                    if(empty($admin)){
                        # 管理员不存在，token违法
                        Code(801, "非法身份登录");
                    }else{
                        if(isset($user["pid"])){
                            return [
                                "id" => $user["aid"],
                                "pid" => $user["pid"],
                                "table" => $user["table"]
                            ];
                        }else{
                            return [
                                "id" => $user["aid"],
                                "table" => $user["table"]
                            ];
                        }
                    }
                }
            }else{
                # token违法
                Code(801, "非法身份登录");
            }
        }else{
            # token违法
            Code(801, "非法身份登录");
        }
        return false;
    }

    # 用户检查Token
    public function Check($string){
        $str = substr($string,-2);
        if($str === "d2"){
            $new_str = substr($string,0,strlen($string)-2);
            $admin = $this->encrypt($new_str,"D");
            $user = json_decode($admin,true);
            $token_info = ['time','id'];
            if(isset($user["time"]) && isset($user["id"])){
                $time = $user["time"];
                if($time+60*60*24*7 < time()){
                    // token过期
                    Code(901, "身份验证已过期，请重新登录");
                }else{
                    $admin = Db::name("user_buy")->where("ub_id",$user["id"])->find();
                    if(empty($admin)){
                        // 管理员不存在，token违法
                        Code(801, "非法身份登录");
                    }else{
                        return [
                            "id" => $user["id"]
                        ];
                    }
                }
            }else{
                // token违法
                Code(801, "非法身份登录");
            }
        }else{
            // token违法
            Code(801, "非法身份登录");
        }
    }

}